package com.bw.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.finance.client.FinanceEsClient;
import com.bw.finance.conf.ResponseResult;
import com.bw.finance.eneity.BidAndLoan.EbidAndLoan;
import com.bw.finance.eneity.es.BorrowBiao;
import com.bw.finance.eneity.invest.BiaoInfo;
import com.bw.finance.eneity.invest.EbankBackPlan;
import com.bw.finance.eneity.locana.EbankBidInfo;
import com.bw.finance.eneity.locana.EbankLoanInfo;
import com.bw.finance.eneity.locana.EbankRepayPlan;
import com.bw.finance.mapper.EbankBidInfoMapper;
import com.bw.finance.service.IEbankBidInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.finance.service.IEbankBorrowerService;
import com.bw.finance.service.IEbankLoanInfoService;
import com.bw.finance.service.IEbankRepayPlanService;
import com.bw.finance.utils.Freemark.FreemarkUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import com.bw.finance.eneity.user.EbankBorrower;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zxx
 * @since 2020-08-19
 */
@Service
public class EbankBidInfoServiceImpl extends ServiceImpl<EbankBidInfoMapper, EbankBidInfo> implements IEbankBidInfoService {

    @Resource
    private IEbankRepayPlanService iEbankRepayPlanService;
    @Autowired
    private IEbankBidInfoService bidInfoService;

    @Resource
    private IEbankBidInfoService iEbankBidInfoService;

    @Autowired
    private EbankBidInfoMapper bidInfoMapper;

    @Autowired
    private FinanceEsClient financeEsClient;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final Logger logger = LoggerFactory.getLogger(ServiceImpl.class);

    @Resource
    private IEbankLoanInfoService iEbankLoanInfoService;

    @Autowired
    private IEbankBorrowerService borrowerService;

    @Override
    public ResponseResult toadd(EbankBidInfo ebankBidInfo) {
        logger.info("添加标开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            ebankBidInfo.setStatus(0);
            iEbankBidInfoService.saveOrUpdate(ebankBidInfo);
            logger.info("添加标结束");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult getebankList(int pagenum, int pagesize, EbankBidInfo bidInfo) {
        ResponseResult result = ResponseResult.FAIL();
        try {
            logger.info("开始列表查询");
            PageHelper.startPage(pagenum, pagesize);
            QueryWrapper<EbankBidInfo> queryWrapper = new QueryWrapper<>();
            if (bidInfo.getBidName() != null) {
                queryWrapper.like("BID_NAME", bidInfo.getBidName());
            }
            List<EbankBidInfo> list01 = bidInfoService.list(queryWrapper);
            PageInfo<EbankBidInfo> pageInfo = new PageInfo<>(list01);
            result.setResult(pageInfo);
            result.setSuccess(true);
            result.setMessage("成功");
        } catch (Exception e) {
            System.out.println(e.toString());
            result.setMessage(e.toString());
        }
        logger.info("列表查询结束");
        return result;
    }

    @Override
    @Transactional
    public ResponseResult updateStatus(long id, int status) {
        ResponseResult result = ResponseResult.FAIL();
        try {
            System.out.println("开始状态修改");
            BiaoInfo biaoInfo = bidInfoMapper.selectone(id);
            EbankBidInfo byId = bidInfoService.getById(id);

            BorrowBiao borrowBiao = new BorrowBiao();
            borrowBiao.setId(String.valueOf(biaoInfo.getId()));
            borrowBiao.setBidName(biaoInfo.getBidName());
            borrowBiao.setBidType(biaoInfo.getBidType());
            borrowBiao.setInterest(biaoInfo.getInterest());
            borrowBiao.setRaiseAmount(biaoInfo.getRaiseAmount());
            borrowBiao.setRepayType(biaoInfo.getRepayType());
            borrowBiao.setTrem(biaoInfo.getTrem());
            borrowBiao.setTremType(biaoInfo.getTermType());
            borrowBiao.setTotalAmount(biaoInfo.getTotalAmount());
            financeEsClient.save(borrowBiao);

            stringRedisTemplate.opsForValue().set("amount:" + id, String.valueOf(biaoInfo.getTotalAmount()));

            String code = "infor.html";//模板页面的名字
            FreemarkUtils.AddToClient(biaoInfo, code);//生成静态页面
            byId.setStatus(status);
            bidInfoService.saveOrUpdate(byId);
            result.setSuccess(true);
            result.setMessage("成功");
        } catch (Exception e) {
            System.out.println(e.toString());
            result.setMessage(e.toString());
        }
        System.out.println("状态修改结束");
        return result;
    }

    @Override
    public ResponseResult getListAll(int pagenum, int pagesize, EbankBorrower borrower) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(pagenum, pagesize);
            Map map = new HashMap<>();
            if (borrower.getFullName() != null) {
                map.put("fullName", borrower.getFullName());
            }
            List<EbidAndLoan> listAll = bidInfoMapper.getAll(map);
            PageInfo pageInfo = new PageInfo(listAll);
            result.setSuccess(true);
            result.setMessage("查询成功!");
            result.setResult(pageInfo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
            return result;
        }
        return result;
    }

    @Override
    public ResponseResult toLookById(Long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            EbankBidInfo bidInfo = bidInfoService.getById(id);
            result.setSuccess(true);
            result.setMessage("查询成功!");
            result.setResult(bidInfo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
            return result;
        }
        return result;
    }

    @Override
    public ResponseResult updateDetail(EbankBidInfo bidInfo) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            bidInfoService.saveOrUpdate(bidInfo);
            result.setSuccess(true);
            result.setMessage("保存成功!");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
            return result;
        }
        return result;
    }

    @Override
    public ResponseResult biaocheckmg(int pagenum, int pagesize, EbankBidInfo bidInfo) {
        logger.info("招标管理列表开始查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(pagenum, pagesize);
            QueryWrapper<EbankBidInfo> queryWrapper = new QueryWrapper<>();
            if (bidInfo != null) {//进行模糊

            }
            List<EbankBidInfo> list = bidInfoService.list(queryWrapper);//查询
            BigDecimal bigDecimal = new BigDecimal(100);
//            BigDecimal num = 100;
            for (EbankBidInfo e : list) {
                e.setTotalAmount(iEbankLoanInfoService.getById(e.getLid()).getTotalAmount());//查询借款金额并赋值
                e.setJd(e.getRaiseAmount().divide(e.getTotalAmount()).multiply(bigDecimal));
            }
            PageInfo<EbankBidInfo> pageInfo = new PageInfo<>(list);//分页
            logger.info("招标管理列表结束查询");
            result.setMessage("招标管理列表查询成功");
            result.setResult(pageInfo);//返回结果集
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error("招标管理列表查询异常" + e.toString());
        }
        return result;
    }


//    @Override
//    public ResponseResult updateStatus01(int id, int val) {
//        logger.info("招标管理列表开始审核");
//        ResponseResult result = ResponseResult.SUCCESS();
//        try {
//            iEbankBidInfoService.saveOrUpdate(iEbankBidInfoService.getById(id).setStatus(val));//状态修改
//            logger.info("招标管理列表结束审核");
//            result.setMessage("招标管理列表审核成功");
//        } catch (Exception e) {
//            result.setSuccess(false);
//            result.setMessage(e.toString());
//            logger.error("招标管理列表查询异常" + e.toString());
//        }
//        return result;
//    }

   /* @Override
    public ResponseResult getborrowall(int pagenum, int pagesize, EbankBorrower borrower) {
        logger.info("借款信息查询开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(pagenum, pagesize);
            Map map = new HashMap<>();
            if (borrower.getFullName() != null) {
                map.put("fullName", borrower.getFullName());
            }
            List<EbankLoanInfo> listAll = iEbankLoanInfoService.jklist(map);
            PageInfo pageInfo = new PageInfo(listAll);
            result.setSuccess(true);
            result.setMessage("查询成功!");
            result.setResult(pageInfo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error("借款信息查询结束",e.toString());
        }
        return result;
    }
*/
    //0是天,1是月
    @Override
    @Transactional
    public ResponseResult updateStatus01(int id, int val) {//标的id以及借款
        logger.info("招标管理列表开始审核");
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            EbankBidInfo ebankBidInfo = iEbankBidInfoService.getById(id).setStatus(val);//获取标的对象，设置状态
            iEbankBidInfoService.saveOrUpdate(ebankBidInfo);//状态修改
            EbankLoanInfo byId = iEbankLoanInfoService.getById(ebankBidInfo.getLid());//获取借款信息

            if(val==7){//val==7是标满审核通过的标
                //判断借款信息的类型 0一次性还款 1等额本金 2等额本息
                if(byId.getRepayType()==0) {//一次性还款
                    if (byId.getTermType() == 0) {//天
                        if (byId.getTermType() == 0) {//天
                            BigDecimal bigDecimal = new BigDecimal(360);
                            BigDecimal decimal = new BigDecimal(100);
                            BigDecimal trem = new BigDecimal(byId.getTrem());//借款期限
                            BigDecimal backamount = byId.getTotalAmount().add(byId.getTotalAmount().multiply(byId.getInterest().divide(decimal, 4, BigDecimal.ROUND_HALF_UP).divide(bigDecimal, 4, BigDecimal.ROUND_HALF_UP)).multiply(trem));//应回款金额
                            EbankRepayPlan repayPlan = new EbankRepayPlan();
                            repayPlan.setLid(byId.getId());
                            repayPlan.setRepayNum(1);//期数
                            repayPlan.setRepayNo(1);
                            repayPlan.setRepayAmount(backamount);
                            repayPlan.setCapital(byId.getTotalAmount());
                            repayPlan.setInterest(byId.getTotalAmount().multiply(byId.getInterest().divide(decimal, 4, BigDecimal.ROUND_HALF_UP).divide(bigDecimal, 4, BigDecimal.ROUND_HALF_UP)).multiply(trem));//回款利息
                            repayPlan.setArAmount(new BigDecimal(0));//已回款金额
                            repayPlan.setIsDue(0);
                            repayPlan.setDueDay(0);
                            repayPlan.setStatus(0);
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(new Date());
                            cal.add(Calendar.DAY_OF_MONTH, byId.getTrem());
                            repayPlan.setRepayDate(cal.getTime());
                            iEbankRepayPlanService.saveOrUpdate(repayPlan);
                        }
                        if (byId.getTermType() == 1) {//月
                            BigDecimal bigDecimal = new BigDecimal(12);
                            BigDecimal decimal = new BigDecimal(100);
                            BigDecimal trem = new BigDecimal(byId.getTrem());//借款期限
                            BigDecimal backamount = byId.getTotalAmount().add(byId.getTotalAmount().multiply(byId.getInterest().divide(decimal, 4, BigDecimal.ROUND_HALF_UP).divide(bigDecimal, 4, BigDecimal.ROUND_HALF_UP)).multiply(trem));//应回款金额
                            EbankRepayPlan repayPlan = new EbankRepayPlan();
                            repayPlan.setLid(byId.getId());
                            repayPlan.setRepayNum(1);//期数
                            repayPlan.setRepayNo(1);
                            repayPlan.setRepayAmount(backamount);
                            repayPlan.setCapital(byId.getTotalAmount());
                            repayPlan.setInterest(byId.getTotalAmount().multiply(byId.getInterest().divide(decimal, 4, BigDecimal.ROUND_HALF_UP).divide(bigDecimal, 4, BigDecimal.ROUND_HALF_UP)).multiply(trem));//回款利息
                            repayPlan.setArAmount(new BigDecimal(0));//已回款金额
                            repayPlan.setIsDue(0);
                            repayPlan.setDueDay(0);
                            repayPlan.setStatus(0);
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(new Date());
                            cal.add(Calendar.DAY_OF_MONTH, byId.getTrem());
                            repayPlan.setRepayDate(cal.getTime());
                            iEbankRepayPlanService.saveOrUpdate(repayPlan);
                        }
                    }
                }
                //判断借款信息的类型 1等额本金
                if(byId.getRepayType()==1){
                    BigDecimal bigDecimal = new BigDecimal(12);//月份
                    BigDecimal decimal = new BigDecimal(100);//用于计算利率
                    BigDecimal trem = new BigDecimal(byId.getTrem());//获取期限
                    BigDecimal ben=byId.getTotalAmount().divide(trem,4,BigDecimal.ROUND_HALF_UP);//每份本金
                    BigDecimal totalmoney=byId.getTotalAmount();//借款金额
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    for (int i = 1; i <=byId.getTrem(); i++) {
                        EbankRepayPlan repayPlan = new EbankRepayPlan();
                        repayPlan.setLid(byId.getId());//借款信息id
                        repayPlan.setRepayNum(byId.getTrem());//总期数
                        repayPlan.setRepayNo(i);//旗号
                        cal.add(Calendar.DAY_OF_MONTH, i * 30);//还款时间
                        repayPlan.setRepayDate(cal.getTime());
                        cal.setTime(new Date());
                        //计算每个月利息
                        //剩余借款金额 * 月利率
                        BigDecimal lixi = totalmoney.multiply(byId.getInterest().divide(decimal, 4, BigDecimal.ROUND_HALF_UP).divide(bigDecimal, 4, BigDecimal.ROUND_HALF_UP));
                        totalmoney = totalmoney.subtract(ben);//剩余借款金额
                        repayPlan.setRepayAmount(ben.add(lixi));//应还款金额
                        repayPlan.setCapital(ben);//本金
                        repayPlan.setInterest(lixi);//利息
                        repayPlan.setArAmount(new BigDecimal(0));
                        repayPlan.setIsDue(0);
                        repayPlan.setDueDay(0);
                        repayPlan.setStatus(0);
                        iEbankRepayPlanService.saveOrUpdate(repayPlan);
                    }
                }
                //判断借款信息的类型  2等额本息
                if(byId.getRepayType()==2){
                    BigDecimal bigDecimal = new BigDecimal(12);
                    BigDecimal decimal = new BigDecimal(100);
                    BigDecimal totalmoney=byId.getTotalAmount();
                    BigDecimal yueinter=byId.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP);//月利率
                    BigDecimal yueinter1=(new BigDecimal(1).add(yueinter)).pow(byId.getTrem());//1+月利率^期限
                    BigDecimal shang=yueinter.multiply(yueinter1).multiply(byId.getTotalAmount());
                    BigDecimal xia=yueinter1.subtract(new BigDecimal(1));
                    BigDecimal yueback=shang.divide(xia,4,BigDecimal.ROUND_HALF_UP);//每月还款额
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    for(int i = 1; i <=byId.getTrem(); i++){
                        EbankRepayPlan repayPlan = new EbankRepayPlan();
                        repayPlan.setLid(byId.getId());
                        repayPlan.setRepayNum(byId.getTrem());
                        repayPlan.setRepayNo(i);
                        cal.add(Calendar.DAY_OF_MONTH, i * 30);
                        repayPlan.setRepayDate(cal.getTime());
                        cal.setTime(new Date());
                        repayPlan.setRepayAmount(yueback);
                        BigDecimal lixi=totalmoney.multiply(byId.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP));
                        BigDecimal ben=yueback.subtract(lixi);
                        repayPlan.setCapital(ben);
                        totalmoney=totalmoney.subtract(ben);
                        repayPlan.setInterest(lixi);
                        repayPlan.setArAmount(new BigDecimal(0));
                        repayPlan.setIsDue(0);
                        repayPlan.setDueDay(0);
                        repayPlan.setStatus(0);

                        iEbankRepayPlanService.saveOrUpdate(repayPlan);
                    }
                }
                byId.setStatus(7);
                iEbankLoanInfoService.saveOrUpdate(byId);
                //对借款人放款
                EbankBorrower borrower = borrowerService.getById(byId.getBorrowerId());
                BigDecimal yueguan=byId.getTotalAmount().multiply(byId.getManageRate().divide(new BigDecimal(100),4,BigDecimal.ROUND_HALF_UP));
                borrower.setBalance(borrower.getBalance().add(byId.getTotalAmount().subtract(yueguan)));
                borrowerService.saveOrUpdate(borrower);
            }
            byId.setStatus(8);//改为审核不通过的状态
            iEbankLoanInfoService.saveOrUpdate(byId);
            logger.info("招标管理列表结束审核");
            result.setMessage("招标管理列表审核成功");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error("招标管理列表查询异常"+e.toString());
        }
        return result;
    }

}
